'use strict';
import Config, { USER_ORIENTED } from '@/util/config';
import { CHATTER_TO, MSG_TYPE, rongEvent } from './messaging';
import {
  // getCurrentUserProfile,
  rongGetChatterProfile,
  uniGetStorageSync,
} from '../funcs';
import { CURRENT_USER_KEY, uniShowToast } from '../misc';

/**
 * 在使用 IMLib 的能力之前，必须先调用 IMLib 的初始化接口，且务必保证该接口在应用全生命周期内仅被调用一次。
 * @type {*}
 */
export const RongIMLib = require('../newSDK/rongIM/RongIMLib-3.0.7.2-dev.min.js');

export let imService = RongIMLib.init({
  appkey: Config.RongCloudAppKey,
});

// cloudContextInit();

export async function cloudContextInit() {
  imAddEventListen();
  return imService;
}

// 注册监听事件
export function imAddEventListen() {
  imService.watch({
    // 监听会话列表变更事件
    conversation: async function (event) {
      console.log("监听会话列表变更事件：",event);
    },
    // 监听消息通知
    message(event) {
      // 新接收到的消息内容
			console.log("监听消息通知：",event)
      let message = event.message;
      uni.$emit(rongEvent.chattingMessageSuccess, message);

      function changeErrorInSdk() {
        if (message.senderUserId === message.targetId) {
          message.targetId = uniGetStorageSync(CURRENT_USER_KEY).id.toString();
        }
      }

      // changeErrorInSdk()
    },
    // 监听 IM 连接状态变化
    status(event) {
      // console.log('connection status:', event.status);
    },
    // 监听聊天室 KV 数据变更
    chatroom(event) {
      /**
       * 聊天室 KV 存储数据更新
       * @example
       * [
       *  {
       *    "key": "name",
       *    "value": "我是小融融",
       *    "timestamp": 1597591258338,
       *    "chatroomId": "z002",
       *    "type": 1 // 1: 更新（ 含:修改和新增 ）、2: 删除
       *  },
       * ]
       */
      const updatedEntries = event.updatedEntries;
    },
    expansion(event) {
      /**
       * 更新的消息拓展数据
       * @example {
       *    expansion: { key: 'value' },      // 设置或更新的扩展值
       *    messageUId: 'URIT-URIT-ODMF-DURR' // 设置或更新扩展的消息 uid
       * }
       */
      const updatedExpansion = event.updatedExpansion;
      /**
       * 删除的消息拓展数据
       * @example {
       *    deletedKeys: ['key1', 'key2'],    // 设置或更新的扩展值
       *    messageUId: 'URIT-URIT-ODMF-DURR' // 设置或更新扩展的消息 uid
       * }
       */
      const deletedExpansion = event.deletedExpansion;
    },
  });
}

// 连接服务
export async function connectRongCloud() {
  return new Promise(async function (resolve, reject) {
    let currentUser = uniGetStorageSync(CURRENT_USER_KEY) || {};
    // console.log('currentUser: ', currentUser.rongcloud_token)
	// if (!currentUser.rongcloud_token && !didntLoggedIn(false)) {
    // if (!currentUser.rongcloud_token) {
    //   currentUser = await getCurrentUserProfile();
    // }
    if (!currentUser.id) {
      // 本地没有用户
      resolve();
    } else {
      let rongcloud_token = currentUser.rongcloud_token;
      // console.log('currentUser.rongcloud_token: ', rongcloud_token);
      if (!rongcloud_token) reject({ msg: '没有rongcloud_token' });
      var option = {
        token: rongcloud_token,
      };
	  console.log('rongcloud_token', rongcloud_token);
      imService.connect(option)
        .then((user) => {
          console.log('链接成功: ', user);
          uni.$emit(rongEvent.connectSuccess);
          resolve(user);
        })
        .catch((error) => {
          if (error.code !== 34001) {
            console.log('链接失败: ', error.code, error.msg);
            reject(error);
          }
          resolve();
        });
    }
  });
}

// 获取会话对方id
export function getOppositeIdFrom(conversation) {
  let { latestMessage } = conversation;
  return getOppoIdFrom(latestMessage);
}

// 根据消息获取对方id
export function getOppoIdFrom(message) {
  if (!message) return;
  let my_rongcloud_id = uniGetStorageSync(CURRENT_USER_KEY).rongcloud_id;

  if (message.senderUserId !== my_rongcloud_id) {
    // 消息发送者id 等于我的id
    return message.senderUserId;
  } else {
    return message.targetId;
  }
}

//获取全部会话,
export async function getAllConversation() {
  return new Promise((resolve, reject) => {
    imService.Conversation.getList()
      .then(function (conversationList) {
        // console.log('获取会话列表成功', conversationList);
        if (conversationList && conversationList.length < 1)
          resolve(conversationList || []);
        // console.log('fetch profile')
        let proArray = [];

        for (let conversation of conversationList) {
          let profilePromise = rongGetChatterProfile(
            getOppositeIdFrom(conversation)
          );
          proArray.push(profilePromise);
        }

        Promise.all(proArray).then((resProfileArr) => {
          for (
            let index = 0, len = resProfileArr.length;
            index < len;
            index++
          ) {
            conversationList[index].chatterInfo = resProfileArr[index];
            // console.log(conversationList[index].chatterInfo);
          }
          resolve(conversationList);
        });
      })
      .catch((res) => {
        connectRongCloud(); // 获取失败通常是没有连接
        uni.$once(rongEvent.connectSuccess, () => {
          return getAllConversation();
        });
        // console.log('get all conversation failed: ', res)
      });
  });
}


// 发送文本
export function cloudSendMessage(msgObj, messageType, cb, opt) {
  let toId = getChatter().rongcloud_id; // 需要传字符串

  // console.log('发送给：', toId)
  if (!messageType) {
    messageType = MSG_TYPE().TEXT;
  }

  let pushContent = 'user 发送了一条消息';
  let pushData = 'Push 通知时附加信息';
  var conversation = imService.Conversation.get({
    targetId: toId,
    type: RongIMLib.CONVERSATION_TYPE.PRIVATE,
  });
  return new Promise((resolve) => {
    conversation
      .send({
        messageType: messageType, // 填写开发者定义的 messageType
        content: msgObj, // 填写开发者定义的消息内容
        isPersited: true, // 是否存储在服务端,默认为 true // isPersited没有写错
        isCounted: true, // 是否计数. 计数消息接收端接收后未读数加 1，默认为 true
        pushContent: pushContent, // Push 显示内容
        pushData: pushData, // Push 通知时附加信息, 可不填
        isStatusMessage: false, // 设置为 true 后 isPersited 和 isCounted 属性失效
        disableNotification: false, // 设置为 true 后移动端不会收到 Push 信息和本地通知提醒
        ...opt, // 解构其他
      })
      .then(function (message) {
        console.log('发送成功', message)
        uni.$emit(rongEvent.chattingMessageSuccess, message);
        resolve(message);
      })
      .catch((res) => {
        console.log('发送失败: ', res);
        if (res.code === 20604) {
          uniShowToast('发送频率过高~');
        } else if (res.code === 30001) {
          uniShowToast('发送失败', false);
          connectRongCloud();
        }
      });
  });
}

/**
 * 发送图片
 */
export const uploadCallbacks = {
  onProgress: function (loaded, total) {
    var percent = Math.floor((loaded / total) * 100);
    console.log('已上传: ', percent);
  },
  onCompleted: function (data) {
    // 上传完成, 调用 getFileUrl 获取文件下载 url
    console.log('上传成功: ', data);
  },
  onError: function (error) {
    console.error('上传失败', error);
  },
};

// 发送文件之前需要获取token, 默认发送文件类型为image
/**
 * 融云官方FILE_TYPE:
 IMAGE: 1,
 AUDIO: 2,
 VIDEO: 3,
 FILE: 4
 * @param fileType
 */
export function beforeForSendFile(fileType) {
  return new Promise((resolve) => {
    imService.getFileToken(fileType || RongIMLib.FILE_TYPE.IMAGE)
      .then(function (data) {
        // console.log('for file: ', data)
        resolve(data);
      })
      .catch(function (error) {
        console.log('获取上传 token 失败', error);
      });
  });
}

/**
 * @desc 获取单人的历史消息,
 *  逻辑: 从服务器获取所有消息, 如果未读消息超过20条就获取所有未读消息,
 * @future-version: 从远端获取所有历史消息,
 * @param rongcloud_id
 * @param count
 * @returns {Promise<>}
 *    {list: historyMessageList, hasMore: whether has more history, count: 消息数量}
 */
export function getHistoryMsg(rongcloud_id, count = 20) {
  let toId = rongcloud_id || getChatter().rongcloud_id;
  let historyListFromStorage = [];
  var option = {
    timestrap: +new Date(),
    count: count,
  };
  var conversation = imService.Conversation.get({
    targetId: toId,
    type: RongIMLib.CONVERSATION_TYPE.PRIVATE,
  });
  conversation.read();
  return conversation.getMessages(option);
}

// chatterInfo
export function getChatter() {
  return (
    uniGetStorageSync(CHATTER_TO) || {
      rongcloud_id: '',
    }
  );
}

/**
 * 当前已存在的会话列表数据, 所有发送人的发送数据
 */
function getExistedConversationList() {
  return new Promise((resolve) => {
    imService.Conversation.getList().then(function (conversationList) {
      resolve(conversationList);
    });
  });
}

/**
 *
 * @param targetId
 * @param timeStamp
 * @return Promise<*[]>
 */
export function getMoreHistory(timeStamp) {
  let toId = getChatter().rongcloud_id; // 需要传字符串
  var conversation = imService.Conversation.get({
    targetId: toId,
    type: RongIMLib.CONVERSATION_TYPE.PRIVATE,
  });
  var option = {
    timestrap: timeStamp,
    count: 20,
  };

  // result = {list, hasMore: '还有更多吗'}
  return conversation.getMessages(option);
}

export function clearConversationUnread(targetId) {
  if (!targetId) return;
  var conversation = imService.Conversation.get({
    targetId: targetId,
    type: RongIMLib.CONVERSATION_TYPE.PRIVATE,
  });
  return conversation.read().then(function () {
    // console.log('清除未读数成功'); // im.watch conversation 将被触发
  });
}

export async function initRongCloud() {
	console.log("荣测试1",uniGetStorageSync(CURRENT_USER_KEY))
	await cloudContextInit();
	await connectRongCloud();
	let status = true;
	let user_rcid = uniGetStorageSync(CURRENT_USER_KEY).rongCloud_id;
	// 注册事件: 有新消息就更新全局会话列表
	updateTabBarBadge()
	uni.$on(rongEvent.chattingMessageSuccess, (message) => {
		// 消息类型为RC:SRSMsg,清除未读数
		console.log(message.senderUserId+" "+user_rcid)
		if (message.senderUserId.toString() != user_rcid) {
			if (message.messageType != "RC:SRSMsg") {
				status = false;
				let conversation = imService.Conversation.get({
					targetId: message.targetId,
					type: RongIMLib.CONVERSATION_TYPE.PRIVATE
				});
				// console.log(imService.conversation.prototype.getUnreadCount())
				// console.log("unread",imService.Conversation.getUnreadCount(conversation)) 
				updateTabBarBadge()
				setTimeout(() => {
					// 进行一次全局会话更新，太快的话全局更新会话不是最新的
					// this.updateGlobalConversation();
					// this.pushSystemNotification(message);
					console.log("推送未读",message)
				}, 300);
			}
		} else {
			if (message.messageType == "RC:SRSMsg") {
				// console.log("触发多端清除未读数");
				console.log("推送已读",message)
				let conversation = imService.Conversation.get({
					targetId: message.targetId,
					type: RongIMLib.CONVERSATION_TYPE.PRIVATE
				});
				// conversation.read();
				// this.updateTabBarBadge();
			}
		}
	});
}

function updateTabBarBadge() {
	// console.log('sConversationList: ', this.sConversationList)
	let total = 0;
	let managerRongId = "merchant_v1_" + uni.getStorageSync("userinfo").stewardId
	let conversation = imService.Conversation.get({
		targetId: managerRongId,
		type: RongIMLib.CONVERSATION_TYPE.PRIVATE
	});
	conversation.getUnreadCount().then(res => {
				total = res
				if (total > 0) {
					if (total > 99) {
						total = '...';
					}
					uni.setTabBarBadge({
						index: 1,
						text: total.toString(),
					});
				} else {
					// console.log('清空 badge');
					uni.removeTabBarBadge({
						index: 1,
					});
				}
            }).catch(err => {
                console.log(err)//此处返回值是上面reject(err);的数据
            })
}

